import { defineStore } from 'pinia'
import { textLanguageStore } from '@/stores/text.js'
import http from '@/utils/uc-http'
import { http as https } from '@/utils/http'
import { http as envhttps } from '@/utils/env-http'
import logo from '@/assets/logo/logo.png'
import loginlogo from '@/assets/login/logo.png'
import logo77 from '@/assets/logo/77-logo.png'
import loginlogo77 from '@/assets/login/77-logo.png'


const TOKEN_KEY = 'token'

export const useUserStore = defineStore('user', () => {
  const user = ref(JSON.parse(localStorage.user || '{}'))
  const token = ref(localStorage[TOKEN_KEY])
  const route = useRoute()
  const router = useRouter()
  const showerrordialog = ref(false)
  const userInfo = ref(null)
  const packageJs = ref({})
  const logostyletype = ref(1)

  const IPList = ref([])
  const activeIp = ref('')
  const apiurls = ref({
    VITE_APP_UC_API: 'http://47.76.250.92:8808/api/uc',
    VITE_APP_API: 'http://47.76.250.92:9995/sp',
    VITE_APP_TEST_API: 'http://47.76.250.92:9997/sp'
  })



  const languageStore = textLanguageStore()
  const language = reactive({
    type: 'zh',
    data: {},
    show: true
  })

  const settingData = ref({
    general: {
      timezone: {}
    },
    bc_types: [],
    default: {},
    hint: {
      begin: {},
      goal: {},
      red_card: {},
      order_fulfil: {},
      order_break: {},
    }
  })

  // 判断是否登录
  const checkLogin = (isGoLogin = true) => {
    token.value = localStorage[TOKEN_KEY]


    if (token.value) {
      if (packageJs.value.plantcode == undefined) {
        setTimeout(() => {
          checkInfo()
        }, 500);
      }
      return true
    } else {
      if (isGoLogin) logout(true)
      return false
    }
    // return true
  }

  // 跳转登录页面
  function goLogin(isRedirect = true) {
    const query = {}

    // 登录成功自动返回
    if (isRedirect) query.redirect = encodeURIComponent(location.pathname + location.search) // NOTE 这里用的location，route.path可以被拦截跳转

    router.replace({
      path: '/login',
      query,
    })

    // location.href = location.href.split('#/')[0] + '/#/login'
  }

  // 登录成功
  const loginSuccess = async options => {
    user.value = options
    token.value = options.accessToken

    localStorage.user = JSON.stringify(options)


    localStorage.ql_admin_gid = options.gid
    localStorage.ql_admin_gname = options.gname
    localStorage.ql_admin_roles = options.username
    localStorage[TOKEN_KEY] = token.value
    localStorage.ql_admin_uid = options.uid
    getuserconfig(1)
    // router.replace({
    //   path: '/',
    // })
  }



  // 获取用户信息
  const getUserInfo = () => {
    return Promise.resolve()
    // return getUserInfoApi().then(res => {
    //   userInfo.value = res.data
    //   return res.data
    // })
  }

  // 退出
  const logout = isRedirect => {
    // localStorage.clear()
    localStorage.removeItem(TOKEN_KEY)
    localStorage.removeItem('user')

    user.value = null
    userInfo.value = null
    token.value = null

    goLogin(isRedirect)
  }

  // 判断账号是否有效
  const checkInfo = async () => {

    if (!token.value) return
    let mac = await window.electron.getMacAddress();


    if (packageJs.value.plantcode) {
      // console.log(token.value);

      http.post('/user_check', {
        token: token.value,
        plant_code: `${packageJs.value.plantcode}=${packageJs.value.plantcode2}`,
        mac: mac,
      }).then((res) => {
        user.value = res


        localStorage.user = JSON.stringify(res)
        localStorage.ql_admin_gid = res.gid
        localStorage.ql_admin_gname = res.gname
        localStorage.ql_admin_roles = res.username
        localStorage.ql_admin_uid = res.uid
        getuserconfig(0)
      })
    }


  }

  const openerrordialog = () => {
    showerrordialog.value = true
  }

  const savepackageJs = (packagejs) => {
    packageJs.value = packagejs
  }

  const logoimg = () => {
    let productname = packageJs.value.productName
    let logoimg
    switch (productname) {
      case 'sp':
        logoimg = logo
        logostyletype.value = 1
        break
      case 'SuperPlace':
        logoimg = logo77
        logostyletype.value = 2
        break
      default:
        break
    }
    return logoimg
  }

  const loginlogoimg = () => {
    let productname = packageJs.value.productName
    let logoimg
    switch (productname) {
      case 'sp':
        logoimg = loginlogo
        logostyletype.value = 1
        break
      case 'SuperPlace':
        logoimg = loginlogo77
        logostyletype.value = 2
        break
      default:
        break
    }
    return logoimg
  }
  const getlanguage = () => {
    console.log(languageStore.textjson);

    language.data = languageStore.textjson[language.type]
    localStorage.sp_language = language.type
  }
  const changelanguage = () => {
    language.show = false
    language.data = languageStore.textjson[language.type]
    localStorage.sp_language = language.type
    if (language.show == false) {
      window.electron.getRelaunch()
    }

  }

  const getuserconfig = (num) => {
    https.get('/config/get_user_config').then(res => {

      if (res.data == null) {
        let navlanguage = navigator.language || navigator.userLanguage
        let a = {
          general: {
            timezone: {
              country: "China",
              country_zh: "中国",
              country_abbreviation: "CN",
              country_timezones: "Asia/Shanghai"
            },
            language: navlanguage == 'zh-CN' ? 'zh' : 'en',
            odds_type: "HongKong"
          },
          bc_types: ['hga'],
          default: {
            max_stake: 10000,
            default_stake: 100,
            order_second: 5
          },
          hint: {
            begin: {
              hint: 0,
              sound: 1
            },
            goal: {
              hint: 1,
              sound: 0
            },
            red_card: {
              hint: 1,
              sound: 0
            },
            order_fulfil: {
              hint: 1,
              sound: 1
            },
            order_break: {
              hint: 0,
              sound: 0
            }
          }
        }
        if (user.value.products.data_feed) {
          user.value.products.data_feed.list.forEach(item => {
            a.bc_types.push(item.attr_code)
          });
        }



        https.post("/config/set_user_config", a).then((res) => {

          settingData.value = a
          language.type = a.general.language
          changelanguage()

        })
      } else {
        settingData.value = res.data
        language.type = res.data.general.language
        getlanguage()
        console.log(num);

        if (num == 1) {
          window.electron.getRelaunch()
        }

      }
    }).catch(() => {
      if (num == 1) {

        window.electron.getRelaunch()

      }
    })
  }


  // 获取ip列表
  const getIps = () => {
    let body = {
      plant_code: 'super_place'
    }
    envhttps.post('/env', body).then(res => {
      let data = JSON.parse(JSON.stringify(res))
      data.forEach(item => {
        item.speed = -1
        if (item.default == 1) {
          activeIp.value = item.url
        }
      });
      IPList.value = data
      setTimeout(() => {
        window.electron.openlistentcp(JSON.stringify(IPList.value))
      }, 1000);
    })


    window.electron.ipSpeed((event, msg) => {
      IPList.value = msg
    })

  }



  checkInfo()
  getIps()
  setInterval(checkInfo, 30 * 1000)

  return {
    user,
    userInfo,
    token,
    showerrordialog,
    packageJs,
    logostyletype,
    settingData,
    language,
    IPList,
    activeIp,
    apiurls,

    checkLogin,
    loginSuccess,
    goLogin,
    getUserInfo,
    logout,
    openerrordialog,
    savepackageJs,
    logoimg,
    loginlogoimg,
    changelanguage,
    getlanguage
  }
})
